<?php

/**
 * 商品管理控制器
 * |--品牌
 * |--商品
 * |--需求
 */
namespace app\avikcm\controller;
use think\Db;
use think\facade\Request;

class Goods extends Common
{
    public function initialize()
    {
        parent::initialize();
    }


    /* 列表模块 */
    public function lists(){
        if(Request::isAjax()){
            $brand_id = input('post.brand_id');
            $key = input('post.key');
            $where [] = ['i.del','=',0];
            if ($key) {
                $where[] = ['i.name', 'like', "%" . $key . "%"];
            }
            if($brand_id){
                $where[] = ['i.brand_id','=',$brand_id];
            }
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list = db('goods_info')->alias('i')
                ->join('goods_brand b', 'b.id = i.brand_id')
                ->field('i.*,b.title as brand_name')
                ->where($where)
                ->order('i.sort', 'desc')
                ->order('i.id', 'desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $brand = db('goods_category')->where(['del'=>0,'pid'=>0])->select();
        $this->assign('brand',$brand);
        return $this->fetch();
    }

    public function getCategory(){
        $id = input('id');
        $lists = db('goods_category')->where(['del'=>0,'pid'=>$id])->select();
        return $lists;
    }

    public function add(){
        if(request()->isPost()){
            $data = Request::except('file');
            $data['create_time'] = date('Y-m-d H:i:s');
            if(empty($data['agent_product_id']) && empty($data['category_one'])){
                return $result = ['code' => 0, 'msg' => '加盟商分类或普通用户商品分类必须选择其中一种!'];
            }
            $insert_id = Db::table('goods_info')->insertGetId($data);
            return ['code'=>1,'msg'=>'添加成功!','url'=>url('lists'),'id' => $insert_id];
        }
        $brand = db('goods_category')->where(['del'=>0,'pid'=>0])->select();
        $this->assign('title','新增商品');
        $this->assign('pic','');
        $this->assign('brand',$brand);
        $this->assign('agent_goods_category',config('agent_goods_category'));
        $this->assign('info','null');
        return $this->fetch('form');
    }

    public function edit(){
        if(request()->isPost()){
            $data = Request::except('file');
            $res = db('goods_info')->where('id',$data['id'])->update($data);
            return json(['code' => 1, 'msg' => '保存成功!', 'url' => url('lists'), 'id' => $data['id']]);
        }else{
            $id = input('id');
            $info = db('goods_info')->where('id',$id)->find();
            $brand = db('goods_category')->where(['del'=>0,'pid'=>0])->select();
            $category_one_list = db('goods_category')->where(['pid'=>$info['brand_id']])->select();
            $category_two_list = db('goods_category')->where(['pid'=>$info['category_one']])->select();
            $pic = db('goods_info_pic')->where('gid',$id)->select();
            // 规格
            $sku_data = $html = [];
            if($info['sku']){
                $sku_data_exp = explode('#',$info['sku']);// 颜色,尺码#白色,红色-S,M
                $key_data = explode(',',$sku_data_exp[0]);
                $val_data = explode('-',$sku_data_exp[1]);
                foreach ($key_data as $k1=>$v1){
                    $sku_data[$k1]['key'] = $v1;
                    $sku_data[$k1]['desc'] = $val_data[$k1];
                    $v2_data = explode(',',$val_data[$k1]);
                    $sku_data[$k1]['val'] = $v2_data;
                }
                $html = $this->getSkuHtml($info['id'],$sku_data_exp[0],$sku_data_exp[1]);
            }
            $this->assign('title','编辑商品');
            $this->assign('pic',$pic);
            $this->assign('brand',$brand);
            $this->assign('category_one_list',$category_one_list);
            $this->assign('category_two_list',$category_two_list);
            $this->assign('info',json_encode($info,true));
            $this->assign('baseInfo',$info);
            $this->assign('agent_goods_category', config('agent_goods_category'));
            $this->assign('sku_data',$sku_data);
            $this->assign('sku_html',$html);
            return $this->fetch('form');
        }
    }

    public function takeSkuValue(){
        $parent = input('parent');
        $value = input('value');
        if(!empty($parent)){
            $arr = explode(',',$parent);
            if(in_array($value,$arr)){
                $key = array_search($value,$arr);
                unset($arr[$key]);
            }
            return implode(',',$arr);
        }else{
            return "";
        }
    }

    // 保存规格
    public function saveSku(){
        $id = input('id');
        $price_data = explode(',',input('price_data'));
        $agent_price_data = explode(',',input('agent_price_data'));
        $stock_data = explode(',',input('stock_data'));
        $sku_data = db('goods_info')->where('id',$id)->value('sku'); // 颜色,尺码#白色,红色-S,M
        $sku_data_exp = explode('#',$sku_data);
        $data = explode('-',$sku_data_exp[1]);
        $str_data = [];
        foreach ($data as $dk=>$dv){
            $str_data[$dk] = explode(',',$dv);
        }
        $cart = $this->cartesian($str_data);
        if($cart){
            $oldData = db('goods_info_sku')->where('gid', $id)->select();
            $newDescData = [];
            foreach ($cart as $kk=>$vv){
                $desc = "";
                if(is_array($vv)){
                    foreach ($vv as $k=>$v){
                        $desc .= $k == 0 ? $v : ','.$v;
                    }
                }else{
                    $desc = $vv;
                }
                $newDescData[] = $desc;
                $db_data = [
                    'gid' => $id,
                    'desc' => $desc,
                    'price' => $price_data[$kk],
                    'agent_price' => empty($agent_price_data[$kk])? $price_data[$kk]: $agent_price_data[$kk],
                    'stock' => $stock_data[$kk]
                ];
                $is_have = db('goods_info_sku')->where('desc',$desc)->find();
                if($is_have){
                    db('goods_info_sku')->where('id',$is_have['id'])->update($db_data);
                }else{
                    db('goods_info_sku')->insert($db_data);
                }
            }
            foreach ($oldData as $value) {
                if(!in_array($value['desc'], $newDescData)){
                    db('goods_info_sku')->where('gid', $id)->where('desc', $value['desc'])->delete();
                }
            }
            return $result = ['code'=>1,'msg'=>'保存成功'];
        }else{
            return $result = ['code'=>0,'data'=>'操作失败'];
        }
    }

    // 处理商品sku表格html
    public function getSku(){
        $id = input('id');
        $name = input('name');  // 颜色,尺码
        $str = input('str');    // 白色,红色-S,M
        db('goods_info')->where('id',$id)->update(['sku'=>$name.'#'.$str]);
        $html = $this->getSkuHtml($id,$name,$str);
        return $result = ['code'=>1,'data'=>$html];
    }

    public function getSkuHtml($id,$name,$str){
        $db_sku = $name.'#'.$str;
        $key_data = explode(',',$name);
        $data = explode('-',$str);
        foreach ($data as $dk=>$dv){
            $str_data[$dk] = explode(',',$dv);
        }
        $cart = $this->cartesian($str_data);

        $html = '<table class="layui-table table-bordered attr-table" style="width: 70%;"><thead><tr>';
        foreach ($key_data as $key=>$val){
            $html .= '<th>'.$val.'</th>';
        }
        $html .= '<th>售价</th><th>代理商价格</th><th>库存</th></tr></thead><tbody>';
        foreach ($cart as $kk=>$vv){
            $desc = "";
            $html .= '<tr>';
            if(is_array($vv)){
                foreach ($vv as $k=>$v){
                    $html .= '<td style="width: 100px;">'.$v.'</td>';
                    $desc .= $k == 0 ? $v : ','.$v;
                }
            }else{
                $html .= '<td style="width: 100px;">'.$vv.'</td>';
                $desc = $vv;
            }
            $info = db('goods_info_sku')->field('price,agent_price,stock')->where(['gid'=>$id,'desc'=>$desc])->find();
            $price = $info['price'] ? $info['price'] : "";
            $agent_price = $info['agent_price'] ? $info['agent_price'] : "";
            $stock = $info['stock'] ? $info['stock'] : 0;
            $html .= '<td style="width: 150px;"><input class="layui-input sku_price" type="text" value="'.$price.'" /></td>';
            $html .= '<td style="width: 150px;"><input class="layui-input sku_agent_price" type="text" value="'.$agent_price.'" /></td>';
            $html .= '<td style="width: 150px;"><input class="layui-input sku_stock" type="text" value="'.$stock.'" /></td></tr>';
        }
        $html .= '</tbody></table>';
        return $html;
    }

    // 笛卡尔积
    public function cartesian($data=""){
        if(!$data){
            $data = [['s']];
        }
        $len = count($data);

        // 取第一个集合数组值
        $result = $data[0];
        for ($i = 0; $i< $len-1; $i++) {
            $arr1 = $result;
            $result = [];
            // 数组第一个值和第二个值组合
            foreach ($arr1 as $res) {
                //数组第二个值...$i+1
                foreach($data[$i+1] as $sec){
                    if(!is_array($res)) {
                        $res = [$res];
                    }
                    if(!is_array($sec)){
                        $sec = [$sec];
                    }
                    $result[] = array_merge_recursive($res,$sec);
                }
            }
        }
        return $result;
//        print_r($result);
    }

    public function order(){
        $db=db('goods_info');
        $data = input('post.');
        if($db->update($data)!==false){
            return $result = ['code'=>1,'msg'=>'排序更新成功!','url'=>url('index')];
        }else{
            return $result = ['code'=>0,'msg'=>'排序更新失败!'];
        }
    }

    public function del(){
        $id = input('id');
        $res = db('goods_info')->where('id',$id)->update(['del'=>1]);
        if($res){
            $result = ['code'=>1,'msg'=>'删除成功!'];
        }else{
            $result = ['code'=>0,'msg'=>'删除失败!'];
        }
        return $result;
    }
    public function delall(){
        $map[] =array('id','in',input('param.ids/a'));
        db('goods_info')->where($map)->update(['del'=>1]);
        return ['code'=>1,'msg'=>'删除成功!'];
    }

    // 商品图片删除
    public function imgDel(){
        $id = input('id');
        $res = db('goods_info_pic')->where('id',$id)->delete();
        if($res){
            $result = ['code'=>1,'msg'=>'删除成功!'];
        }else{
            $result = ['code'=>0,'msg'=>'删除失败!'];
        }
        return $result;
    }

    //商品多图上传
    public function uploads(){
        $id = input('id');
        if($id){
            $fileKey = array_keys(request()->file());
            // 获取表单上传文件
            $file = request()->file($fileKey['0']);
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])->move('uploads');
            if($info){
                $path=str_replace('\\','/',$info->getSaveName());
                $data = [
                    'gid' => $id,
                    'pic' => '/uploads/'. $path,
                    'create_time' => date('Y-m-d H:i:s')
                ];
                $insert_id = db('goods_info_pic')->insertGetId($data);
                $result['files']['code'] = 0;
                $result['files']['msg'] = '图片上传成功!';
                $result['files']["file"] = '/uploads/'. $path;
                $result['files']['id'] = $insert_id;
                return $result;
            }else{
                // 上传失败获取错误信息
                $result['files']['code'] =1;
                $result['files']['msg'] = '图片上传失败!';
                return $result;
            }
        }else{
            $result['files']['code'] =2;
            $result['files']['msg'] = '请先保存基本信息!';
            return $result;
        }
    }


    /* 需求模块 */

    public function need(){
        if(Request::isAjax()){
            $key = input('post.key');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $paginate = ['list_rows'=>$pageSize,'page'=>$page];
            $list = db('goods_need')->alias('n')->field('n.*,b.title brand_name,u.nickname')
                ->join('users u','u.id = n.uid')
                ->join('goods_brand b','b.id = n.brand_id')
                ->where('n.name','like','%'.$key.'%')
                ->paginate($paginate)->toArray();
            if($list['data']){
                foreach ($list['data'] as $key=>$val){
                    $people = [1=>'男女同款',2=>'男款',3=>'女款',4=>'儿童'];
                    $list['data'][$key]['people_name'] = $people[$val['people']];
                    $list['data'][$key]['status_name'] = $val['status'] == 1 ? '待审核' : '已审核';
                }
            }
            return ['code'=>0,'msg'=>'成功','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }

    public function needLook(){
        $id = input('id');
        $info = db('goods_need')->alias('n')->json(['pics'])
            ->field('n.*,b.title brand_name,u.nickname')
            ->join('users u','u.id = n.uid')
            ->join('goods_brand b','b.id = n.brand_id')
            ->where('n.id',$id)
            ->find();
        $people = [1=>'男女同款',2=>'男款',3=>'女款',4=>'儿童'];
        $info['people_name'] = $people[$info['people']];
        $info['status_name'] = $info['status'] == 1 ? '待审核' : '已审核';
        $this->assign('info',$info);
        $this->assign('title','查看需求');
        return $this->fetch('look');
    }

    public function needCheck(){
        $id = input('id');
        $res= db('goods_need')->where('id',$id)->update(['status'=>2,'check_time'=>date('Y-m-d H:i:s')]);
        if($res){
            return ['code'=>1,'msg'=>'成功'];
        }else{
            return ['code'=>0,'msg'=>'失败'];
        }
    }


}